<template>
  <div>
      <form action="/">
        <van-search
          v-model="searchText"
          show-action
          placeholder="请输入搜索关键词"
          @search="onSearch"
          @cancel="onCancel"
          background="#3296fa"
          @focus="isResultShow=false"
        />
      </form>
      <!-- 搜索结果 输入框输入东西之后按下回车 -->
      <search-result v-if="isResultShow" :searchText="searchText"></search-result>
      <!-- 搜索建议 输入框中有值的时候 -->
      <search-suggestion v-else-if="searchText" :searchText="searchText" @search-event="onSearch"></search-suggestion>
      <!-- 搜索历史 用户还什么都没有输入，就显示搜索历史 -->
      <search-history v-else :searchHistoryArray="searchHistoryArray" @my-click="onSearch"></search-history>

  </div>
</template>
<script>
// 定义一个数组，用来存每次的搜索的历史记录，最新的记录放在最前面 并且不能重复
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
// eslint-disable-next-line
import { getItem, setItem } from '@/utils/storage' // eslint-disable-line
const TOUTIAO_HISTORY = 'TOUTIAO_HISTORY'// 定义一个常量 为什么字母全部大写 因为项目中约定了只要看到全是大写就是一个常量
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory, // eslint-disable-line
    SearchSuggestion, // eslint-disable-line
    SearchResult
  },
  watch: {
    searchHistoryArray: function () {
      setItem(TOUTIAO_HISTORY, this.searchHistoryArray)
    }
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistoryArray: getItem(TOUTIAO_HISTORY) || []
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      this.isResultShow = true
      // indexOf ---> 求索引值，如果值为-1说明没有重复，如果不为-1说明有重复，并且值就是索引值，刚好可以用splice删除
      var index = this.searchHistoryArray.indexOf(val)
      if (index !== -1) {
        this.searchHistoryArray.splice(index, 1)
      }
      this.searchHistoryArray.unshift(val)
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>
<style scoped lang="less">
/deep/ .van-search__action{
  color:#fff;
}

.van-search{
  position: fixed;
  width:100%;
  z-index:1;
}
.van-list{
  padding-top:108px;
}
</style>
